package com.yx.cloud.activity;

import android.Manifest;
import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.iot.base.bean.account.Account;
import com.iot.base.service.req.ModifyUserInfoParam;
import com.iot.base.service.resp.LoginResponse;
import com.iot.base.service.resp.LogoutResponse;
import com.iot.common.utils.Event;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.CountryCodeBean;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.databinding.AccountmanagActivityBinding;
import com.yx.cloud.product.laser.inxni.INXNIConstant;
import com.yx.cloud.utils.AppUtil;
import com.yx.cloud.utils.AtyContainer;
import com.yx.cloud.utils.BitmapUtils;
import com.yx.cloud.utils.CountryCodeUtils;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LanguageUtils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RegularCheckUtils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.utils.UserHeadUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 创建时间 : 2018/12/26.
 * 创建人 :
 * 功能描述 :帐号管理界面
 */
public class AccountManagActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "AccountManagActivity";
    //调取系统摄像头的请求码
    private static final int CAMERA_PERMISSIONS = 6;
    //打开相册的请求码
    private static final int MY_ADD_CASE_CALL_PHONE2 = 7;
    private BottomSheetDialog sheetDialog;
    private Dialog dialog;
    private String mUserAccount = "", nickName = "", type = "", accountNumber = "", contryCode = "", headPic = "";
    private LoadProgressDialog loadProgressDialog;
    private Account account = null;

    private AccountmanagActivityBinding binding;

    @Override
    protected void onCreate() {
        binding = AccountmanagActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }

    private void initData() {
        //自动获取当前国家代码
        loadProgressDialog = new LoadProgressDialog(this);
        //自动获取当前国家代码
        String systemLanguage = LanguageUtils.getSystemLanguage(this);
        String substring = systemLanguage.substring(3, 5);
        ArrayList<CountryCodeBean> codeList = CountryCodeUtils.getCountryCodeList(this);
        for (int i = 0; i < codeList.size(); i++) {
            if (substring.equals("" + codeList.get(i).getLocale())) {
                contryCode = codeList.get(i).getCode() + "";
            }
        }

        account = AppContext.get().getAccount();
        if (account != null) {
            Log.i(TAG, "AccountManagActivity user is null : " + new Gson().toJson(account));
            mUserAccount = account.getAccount();
            binding.tvAccount.setText(mUserAccount);
            if (RegularCheckUtils.isMobile(mUserAccount)) {
                binding.tvAccountmanagerAccount.setText(R.string.MY_Phone);
                type = "phoneNumer";
            } else if (RegularCheckUtils.isEmail(mUserAccount)) {
                binding.tvAccountmanagerAccount.setText(R.string.MY_Email);
                type = "email";
            }

            nickName = account.getNickname();
            if (nickName == null || nickName.equals("")) {
                binding.tvNickName.setText(mUserAccount);
            } else {
                binding.tvNickName.setText(nickName);
            }
            headPic = account.getHeadPicUrl();

            if (account.getHeadPic() != null) {
                binding.headPortrait.setImageBitmap(account.getHeadPic());
            } else {
                binding.headPortrait.setImageResource(R.mipmap.headportrait_icon); //贤者之默认头像
                //从服务器上加载头像
                AppContext.getAccountService().getUserProfile(headPic);
            }

        }
        loadProgressDialog.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                loadProgressDialog.dismiss();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        binding.ivAccountManagReturn.setOnClickListener(this);
        binding.rlNickName.setOnClickListener(this);
        binding.rlAmendPassWord.setOnClickListener(this);
        binding.headPortrait.setOnClickListener(this);
        binding.llHeadPortrait.setOnClickListener(this);
        binding.rlCancelAccount.setOnClickListener(this);
        binding.rlOut.setOnClickListener(this);
        binding.rlAccounPhoneNumberBind.setOnClickListener(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        if (loadProgressDialog != null && loadProgressDialog.isShowing()) {
            loadProgressDialog.dismiss();
        }
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_LOGOUT:
                if (event.isResult()) {
                    //政策隐私标记
                    SharedPrefsUtil.putValue(this, "ServerAndPrivacySign", "ServerAndPrivacySign", false);
                    //保存登录成功标记
                    SharedPrefsUtil.putValue(this, Constants.ISLOG, "isLog", false);
                    SharedPrefsUtil.putValue(this, Constants.USERNAME, "contryCode", "");
                    SharedPrefsUtil.putValue(this, Constants.DEVICEID, "deviceId", "");
                    AppContext.get().getAccount().clear();
                    INXNIConstant.USER_ID = "";
                    AtyContainer.getInstance().finishAllActivity(); //在登录界面点击返回键退出程序
                    Intent_utils.enterIntent(this, LoginActivity.class);
                    finish();
                } else {
                    LogoutResponse response= (LogoutResponse) event.getContent();
                    if (response.getErrorCode()== LoginResponse.ERROR_NETWORK) {
                        ToastUtil.showShort(this,R.string.U_T_Network_Err);
                    }else if (response.getErrorCode()==LoginResponse.ERROR_SERVER) {
                        ToastUtil.showShort(this, getString(R.string.U_T_Server_Err));
                    } else {
                        ToastUtil.showShort(this, response.getData().toString());
                    }
                }
                break;
            case Event.MESSAGE_TYPE_DOWNLOAD_HEADPICTRUE:
                //自动更新头像
                Log.i(TAG, "自动更新头像--------- " + event.isResult());
                if (event.isResult()) {
                    Bitmap bitmap = (Bitmap) event.getContent();
                    binding.headPortrait.setImageBitmap(bitmap);
                } else {
                    binding.headPortrait.setImageResource(R.mipmap.headportrait_icon);
                }
                break;
            case Event.MESSAGE_TYPE_UPLOAD_HEADPICTRUE:
                //上次头像
//                AppContext.getAccountService().getUserInfo();//同步用户信息
                if (!event.isResult()) {
                    ToastUtil.show(AccountManagActivity.this, event.getContent().toString(), Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_SAVE_HEADPICTURE_CACHE:
                //已经把图片缓存到本地
                if (event.isResult()) {
                    //上传头像
                    ModifyUserInfoParam param = ModifyUserInfoParam.newBuilder().icon(UserHeadUtil.getHeadPicturePath()).build();
                    AppContext.getAccountService().modifyUserInfo(param);
                }
                //刷新UI
                showUserHeadImage();
                break;
        }
    }

    /**
     * 退出登录Dialog
     */
    private void outLoginHintDialog(String dialogTitle) {
        dialog = new Dialog(AccountManagActivity.this);
        dialog.setContentView(R.layout.content_centered_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_centered_Confirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_centered_Cancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_centered_dialogTitle);
        mTvDialogTitle.setText(dialogTitle);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                dialog.dismiss();
                loadProgressDialog.show();
                AppContext.getAccountService().logout();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 底部弹框
     */
    private void showDialog() {
        Log.i(TAG, "WZ--1----------showDialog");
        sheetDialog = new BottomSheetDialog(AccountManagActivity.this);
        View view = LayoutInflater.from(this).inflate(R.layout.layout_take_photo, null);

        TextView tvCamera = view.findViewById(R.id.tvCamera);
        tvCamera.setOnClickListener(this);
        TextView tvPhoto = view.findViewById(R.id.tvPhoto);
        tvPhoto.setOnClickListener(this);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        tvCancel.setOnClickListener(this);
        sheetDialog.setContentView(view);
        //设置透明背景
        sheetDialog.getWindow().findViewById(R.id.design_bottom_sheet)
                .setBackgroundResource(android.R.color.transparent);
        sheetDialog.show();
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_accountManagReturn:
                Intent_utils.backIntent(this);
                break;
            case R.id.rl_nickName:
                String nickName = binding.tvNickName.getText().toString().trim();
                Intent amendnickname = new Intent(this, AmendNickNameActivty.class);
                amendnickname.putExtra("nickName", nickName);
                Bundle bundle = new Bundle();
                amendnickname.putExtras(bundle);
                startActivityForResult(amendnickname, 5);
                break;
            case R.id.rl_amendPassWord:
                //修改密码
                Intent change_password = new Intent(this, RetrievePasswordActivity.class);
                change_password.putExtra("user_account", mUserAccount);
                startActivity(change_password);
                break;
            case R.id.headPortrait:
            case R.id.ll_headPortrait:
                showDialog();
                break;
            case R.id.rl_cancelAccount:
                //注销用户账号
                Intent_utils.enterIntentContext(this, CancelAccountActivity.class, "userAccount", mUserAccount);
                break;
            case R.id.rl_out:
                outLoginHintDialog(getResources().getString(R.string.MY_SignOut));
                break;
            case R.id.tvCamera:
                sheetDialogDismiss();
                //"点击了照相";
                //  6.0之后动态申请权限 摄像头调取权限,SD卡写入权限
                //判断是否拥有权限，true则动态申请
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                            CAMERA_PERMISSIONS);
                } else {
                    try {
                        //有权限,去打开摄像头
                        takePhoto();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                break;
            case R.id.tvPhoto:
                //"点击了相册";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                    startActivityForResult(intent, 3);
                } else {
                    //  6.0之后动态申请权限 SD卡写入权限
                    if (ContextCompat.checkSelfPermission(AccountManagActivity.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(AccountManagActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_ADD_CASE_CALL_PHONE2);
                    } else {
                        //打开相册
                        choosePhoto();
                    }
                }
                sheetDialogDismiss();
                break;
            case R.id.tvCancel:
                sheetDialogDismiss();
                break;
        }
    }

    private void takePhoto() throws IOException {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        // 获取文件
        File file = createFileIfNeed(AppUtil.getPackageName(this) + "UserIcon.png");
        //拍照后原图回存入此路径下
        Uri uri;
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
            uri = Uri.fromFile(file);
        } else {
            /**
             * 7.0 调用系统相机拍照不再允许使用Uri方式，应该替换为FileProvider
             * 并且这样可以解决MIUI系统上拍照返回size为0的情况
             */
            uri = FileProvider.getUriForFile(AccountManagActivity.this, AppUtil.getPackageName(this) + ".fileprovider", file);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(intent, 1);
    }

    // 在sd卡中创建一保存图片（原图和缩略图共用的）文件夹
    private File createFileIfNeed(String fileName) throws IOException {
        String fileA = getExternalCacheDir().getAbsolutePath() + "/nbinpic";
        File fileJA = new File(fileA);
        if (!fileJA.exists()) {
            fileJA.mkdirs();
        }
        File file = new File(fileA, fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        return file;
    }

    /**
     * 打开相册
     */
    private void choosePhoto() {
        //这是打开系统默认的相册(就是你系统怎么分类,就怎么显示,首先展示分类列表)
        Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(picture, 3);
    }

    /**
     * activity 选择头像操作后返回
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @SuppressLint("LongLogTag")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        Log.i(TAG, "WZ--ttttttttttttttttttttttttttttttttttt--onActivityResult--------" + requestCode);
        if (requestCode == 5) {
            if (data != null) {
                String mNickName = data.getStringExtra("mNickName");
                if (!"".equals(mNickName)) {
                    binding.tvNickName.setText(mNickName);
                    Constants.nickName = mNickName;
                }
            }
        } else if (requestCode == 1 && resultCode == RESULT_OK) {
            //拍照结果返回  图片已经被替换了 直接刷新界面 上传头像就行
            String state = Environment.getExternalStorageState();
            if (!state.equals(Environment.MEDIA_MOUNTED)) {
                return;
            }

            Event.newBuilder().type(Event.MESSAGE_TYPE_SAVE_HEADPICTURE_CACHE).result(true).send();

        } else if (requestCode == 3 && resultCode == Activity.RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            //把指定URI的文件复制到缓存文件夹
            UserHeadUtil.SavePictureTask savePictureTask = new UserHeadUtil.SavePictureTask();
            savePictureTask.execute(selectedImage);
        }
    }

    /**
     * 根据路径,显示头像
     * <p>
     */
    private void showUserHeadImage() {
        String path = UserHeadUtil.getHeadPicturePath();
        File file = new File(path);
        if (file.exists()) {
            //刷新头像
            Bitmap bitmap = BitmapUtils.compressImage(AccountManagActivity.this, path);
//            AppContext.get().getAccount().setHeadPic(bitmap);
            if (bitmap != null) {
                binding.headPortrait.setImageBitmap(bitmap);
                return;
            }
        }
        binding.headPortrait.setImageResource(R.mipmap.headportrait_icon);
    }

    /**
     * 申请权限回调方法
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_ADD_CASE_CALL_PHONE2) {
            boolean isPermissionDeny = false; //用户是否拒绝权限
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    isPermissionDeny = true;
                }
            }
            if (isPermissionDeny) {
                choosePhoto();
            }
        } else if (requestCode == CAMERA_PERMISSIONS) {
            boolean isPermissionDeny = false; //用户是否拒绝权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                isPermissionDeny = true;
            }
            // LogUtils.i(" : 相机权限 ： " + isPermissionDeny);
            try {
                if (isPermissionDeny) {
                    takePhoto();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void sheetDialogDismiss() {
        if (null != sheetDialog && sheetDialog.isShowing()) {
            sheetDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //禁止划屏关闭界面
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.i(TAG, "keyCode--------  " + KeyEvent.KEYCODE_BACK);
//            AppContext.get().setDeviceVariety("map");
            Intent_utils.backIntent(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
